package com.zzr.demo.redis.service.impl;

import com.sun.org.apache.bcel.internal.generic.NEW;
import com.zzr.demo.redis.service.RankingListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: xiaomi
 * @date: 2021/10/9
 * @description: 新闻排行榜
 */
@Service
@Slf4j
public class NewsRankingListServiceImpl implements RankingListService {

    final String NEWS_RANKING_KEY = "news::ranking";

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean addItem(String name, int score) {
        ZSetOperations<String, String> opsForZSet = stringRedisTemplate.opsForZSet();
        Boolean add = opsForZSet.add(NEWS_RANKING_KEY, name, score);
        return add;
    }

    @Override
    public List<String> getRevRankingList() {
        //使用 name:score 的形式
        List<String> resList = new ArrayList<>();
        ZSetOperations<String, String> opsForZSet = stringRedisTemplate.opsForZSet();
        //ZREVRANGE 根据索引及个数进行排名
        Set<ZSetOperations.TypedTuple<String>> typedTuples = opsForZSet.reverseRangeWithScores(NEWS_RANKING_KEY, 0, -1);
        for (ZSetOperations.TypedTuple<String> item :
                typedTuples) {
            resList.add(item.getValue() + ":" + item.getScore());
        }
        return resList;
    }


}
